import React, {Component} from 'react';
import "../../assets/css/productCateforyAddForm.scss";
import http from "../../http";

class ProductCategoryAddForm extends Component {
	constructor(props) {
		super(props);
		this.state = {
			productCategoryList: [],
			parentId: '0',
			categoryName: ''
		}
	}

	componentDidMount() {
		this.getProductCategoryList()
	}

	submitForm = () => {
		if (this.state.categoryName === '') {
			alert('请输入品类名称！');
			return false;
		}
		http.addCategory({
			parentId: this.state.parentId,
			categoryName: this.state.categoryName
		}).then(res => {
			if (res.status === 0) {
				alert(res.data);
				this.props.history.push('/product-category');
			}
		})
	};

	getProductCategoryList = () => {
		http.getProductCategoryList().then(res => {
			if (res.status === 0) {
				this.setState({
					productCategoryList: res.data
				})
			}
		})
	};

	changeParentId = e => {
		this.setState({
			parentId: e.target.value
		})
	};

	changeCategoryName = e => {
		this.setState({
			categoryName: e.target.value
		})
	};

	render() {
		return (
			<div>
				<div className="home-title">
					<span>品类管理 -- 添加品类</span>
				</div>
				<div className="product-category-form form-wrap row">
					<div className="form-horizontal">
						<div className="form-group">
							<label
								htmlFor="name"
								className="col-md-2 control-label"
							>
								所属品类
							</label>
							<div className="col-md-3">
								<select
									defaultValue={this.state.parentId}
									onChange={this.changeParentId}
									className="form-control cate-select col-md-5"
								>
									<option value="0">/所有</option>
									{
										this.state.productCategoryList.map(item => {
											return <option
												key={item.id}
												value={item.id}
											>
												/所有/{item.name}
											</option>
										})
									}
								</select>
							</div>
						</div>
						<div className="form-group">
							<label
								htmlFor="name"
								className="col-md-2 control-label"
							>
								品类名称
							</label>
							<div className="col-md-4">
								<input
									type="text"
									id="name"
									className="form-control"
									name="name"
									placeholder="请输入品类名称"
									autoComplete="off"
									value={this.state.categoryName}
									onChange={this.changeCategoryName}
								/>
							</div>
						</div>
						<div className="form-group">
							<label className="col-md-2"></label>
							<div className="col-md-10">
								<div className="input-group">
									<button
										onClick={this.submitForm}
										className="btn btn-primary"
									>
										提交
									</button>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		);
	}
}

export default ProductCategoryAddForm;